from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.database import engine
from app.models import *
from app.routers import auth, users, exams, questions, scores, logs
import os
from fastapi.responses import HTMLResponse

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title="在线考试系统",
    description="基于Python + Vue的在线考试系统",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 开发环境允许所有来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
app.include_router(users.router, prefix="/api/users", tags=["用户管理"])
app.include_router(exams.router, prefix="/api/exams", tags=["考试管理"])
app.include_router(questions.router, prefix="/api/questions", tags=["题目管理"])
app.include_router(scores.router, prefix="/api/scores", tags=["成绩管理"])
app.include_router(logs.router, prefix="/api/logs", tags=["日志管理"])

@app.get("/", response_class=HTMLResponse)
async def root():
    student_url = os.getenv("FRONTEND_STUDENT_URL", "http://localhost:3000")
    teacher_url = os.getenv("FRONTEND_TEACHER_URL", "http://localhost:3001")
    admin_url = os.getenv("FRONTEND_ADMIN_URL", "http://localhost:3002")
    
    return f"""
    <html>
        <head><title>在线考试系统</title></head>
        <body>
            <h1>欢迎使用在线考试系统</h1>
            <p><a href="/docs">API 文档</a></p>
            <p><a href="{student_url}">学生端</a></p>
            <p><a href="{teacher_url}">教师端</a></p>
            <p><a href="{admin_url}">管理端</a></p>
        </body>
    </html>
    """

@app.get("/health")
async def health_check():
    return {"status": "healthy", "service": "online-exam-system"}